import { defineStore } from 'pinia'
import { ref } from 'vue'
import { clearToken, getToken, setToken } from '@/utils/auth'
import type { ParentInfo, PhoneLoginReq } from '@/apis/common/type'
import {
  getUserInfo,
  loginByPhone as loginByPhoneApi,
  loginByWxPhone as loginByWxPhoneApi,
} from '@/apis'

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken() || '')
  const userInfo = ref<ParentInfo>()

  // 刷新用户信息
  const refreshUserInfo = async () => {
    const res = await getUserInfo()
    userInfo.value = res.userInfo
  }

  // 验证码登录
  const loginByPhone = async (req: PhoneLoginReq) => {
    const res = await loginByPhoneApi(req)
    setToken(res.token)
    token.value = res.token
  }

  // 微信授权手机登录
  const loginByWxPhone = async (code: string) => {
    const res = await loginByWxPhoneApi(code)
    setToken(res.token)
    token.value = res.token
  }

  const logout = () => {
    token.value = ''
    userInfo.value = null
    clearToken()
    uni.redirectTo({ url: '/pages/login/index' })
  }

  const isLogin = () => {
    return token.value
  }

  return {
    token,
    userInfo,
    isLogin,
    refreshUserInfo,
    loginByPhone,
    loginByWxPhone,
    logout,
  }
}, {
  persist: true,
})
